<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>平台概览</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshData">刷新数据</el-button>
          </div>
          <el-row :gutter="20" class="dashboard-count">
            <el-col :span="6">
              <div class="count-item">
                <div class="count-icon">
                  <svg-icon icon-class="user" />
                </div>
                <div class="count-info">
                  <div class="count-title">用户总数</div>
                  <div class="count-num">{{ overview.userCount }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="count-item">
                <div class="count-icon" style="background-color: #409EFF;">
                  <svg-icon icon-class="peoples" />
                </div>
                <div class="count-info">
                  <div class="count-title">圈子总数</div>
                  <div class="count-num">{{ overview.topicCount }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="count-item">
                <div class="count-icon" style="background-color: #67C23A;">
                  <svg-icon icon-class="documentation" />
                </div>
                <div class="count-info">
                  <div class="count-title">帖子总数</div>
                  <div class="count-num">{{ overview.postCount }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="count-item">
                <div class="count-icon" style="background-color: #E6A23C;">
                  <svg-icon icon-class="tree" />
                </div>
                <div class="count-info">
                  <div class="count-title">分类总数</div>
                  <div class="count-num">{{ overview.categoryCount }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>用户增长趋势</span>
            <el-select v-model="userGrowthDays" size="mini" style="float: right; width: 120px;" @change="getUserGrowthData">
              <el-option label="最近7天" :value="7" />
              <el-option label="最近30天" :value="30" />
              <el-option label="最近90天" :value="90" />
            </el-select>
          </div>
          <div class="chart-container">
            <div ref="userGrowthChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>内容增长趋势</span>
            <el-select v-model="contentStatsDays" size="mini" style="float: right; width: 120px;" @change="getContentStatsData">
              <el-option label="最近7天" :value="7" />
              <el-option label="最近30天" :value="30" />
              <el-option label="最近90天" :value="90" />
            </el-select>
          </div>
          <div class="chart-container">
            <div ref="contentStatsChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>热门圈子排行</span>
            <el-select v-model="hotTopicsLimit" size="mini" style="float: right; width: 120px;" @change="getHotTopicsData">
              <el-option label="前5名" :value="5" />
              <el-option label="前10名" :value="10" />
              <el-option label="前20名" :value="20" />
            </el-select>
          </div>
          <el-table v-loading="hotTopicsLoading" :data="hotTopics" style="width: 100%">
            <el-table-column prop="topicName" label="圈子名称" />
            <el-table-column prop="memberCount" label="成员数" width="100" />
            <el-table-column prop="postCount" label="帖子数" width="100" />
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="goToTopicDetail(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>热门帖子排行</span>
            <el-select v-model="hotPostsLimit" size="mini" style="float: right; width: 120px;" @change="getHotPostsData">
              <el-option label="前5名" :value="5" />
              <el-option label="前10名" :value="10" />
              <el-option label="前20名" :value="20" />
            </el-select>
          </div>
          <el-table v-loading="hotPostsLoading" :data="hotPosts" style="width: 100%">
            <el-table-column prop="title" label="帖子标题" :show-overflow-tooltip="true" />
            <el-table-column prop="viewCount" label="浏览量" width="100" />
            <el-table-column prop="likeCount" label="点赞数" width="100" />
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="goToPostDetail(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>活跃用户排行</span>
            <el-select v-model="activeUsersLimit" size="mini" style="float: right; width: 120px;" @change="getActiveUsersData">
              <el-option label="前5名" :value="5" />
              <el-option label="前10名" :value="10" />
              <el-option label="前20名" :value="20" />
            </el-select>
          </div>
          <el-table v-loading="activeUsersLoading" :data="activeUsers" style="width: 100%">
            <el-table-column prop="userName" label="用户名" />
            <el-table-column prop="nickName" label="昵称" />
            <el-table-column prop="postCount" label="发帖数" width="100" />
            <el-table-column prop="commentCount" label="评论数" width="100" />
            <el-table-column prop="likeCount" label="点赞数" width="100" />
            <el-table-column prop="lastLoginTime" label="最后登录时间" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.lastLoginTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="goToUserDetail(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getOverview, getUserGrowth, getContentStats, getHotTopics, getHotPosts, getActiveUsers, getTrends } from "@/api/quanzi/statistics";

export default {
  name: "Statistics",
  data() {
    return {
      // 概览数据
      overview: {
        userCount: 0,
        topicCount: 0,
        postCount: 0,
        categoryCount: 0
      },
      // 用户增长
      userGrowthDays: 7,
      userGrowthChart: null,
      userGrowthData: {},
      // 内容统计
      contentStatsDays: 7,
      contentStatsChart: null,
      contentStatsData: {},
      // 热门圈子
      hotTopicsLimit: 10,
      hotTopicsLoading: false,
      hotTopics: [],
      // 热门帖子
      hotPostsLimit: 10,
      hotPostsLoading: false,
      hotPosts: [],
      // 活跃用户
      activeUsersLimit: 10,
      activeUsersLoading: false,
      activeUsers: [],
      // 数据趋势
      trendsData: {}
    };
  },
  created() {
    this.getOverviewData();
    this.getUserGrowthData();
    this.getContentStatsData();
    this.getHotTopicsData();
    this.getHotPostsData();
    this.getActiveUsersData();
  },
  mounted() {
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    if (this.userGrowthChart) {
      this.userGrowthChart.dispose();
    }
    if (this.contentStatsChart) {
      this.contentStatsChart.dispose();
    }
  },
  methods: {
    // 刷新所有数据
    refreshData() {
      this.getOverviewData();
      this.getUserGrowthData();
      this.getContentStatsData();
      this.getHotTopicsData();
      this.getHotPostsData();
      this.getActiveUsersData();
      this.$message({
        message: '数据已刷新',
        type: 'success'
      });
    },
    // 获取概览数据
    getOverviewData() {
      getOverview().then(response => {
        this.overview = response.data;
      });
    },
    // 获取用户增长数据
    getUserGrowthData() {
      getUserGrowth(this.userGrowthDays).then(response => {
        this.userGrowthData = response.data;
        this.$nextTick(() => {
          this.initUserGrowthChart();
        });
      });
    },
    // 获取内容统计数据
    getContentStatsData() {
      getContentStats(this.contentStatsDays).then(response => {
        this.contentStatsData = response.data;
        this.$nextTick(() => {
          this.initContentStatsChart();
        });
      });
    },
    // 获取热门圈子数据
    getHotTopicsData() {
      this.hotTopicsLoading = true;
      getHotTopics(this.hotTopicsLimit).then(response => {
        this.hotTopics = response.data;
        this.hotTopicsLoading = false;
      });
    },
    // 获取热门帖子数据
    getHotPostsData() {
      this.hotPostsLoading = true;
      getHotPosts(this.hotPostsLimit).then(response => {
        this.hotPosts = response.data;
        this.hotPostsLoading = false;
      });
    },
    // 获取活跃用户数据
    getActiveUsersData() {
      this.activeUsersLoading = true;
      getActiveUsers(this.activeUsersLimit).then(response => {
        this.activeUsers = response.data;
        this.activeUsersLoading = false;
      });
    },
    // 初始化用户增长图表
    initUserGrowthChart() {
      if (this.userGrowthChart) {
        this.userGrowthChart.dispose();
      }
      
      this.userGrowthChart = echarts.init(this.$refs.userGrowthChart);
      
      // 这里使用模拟数据，实际应该使用API返回的数据
      const dates = this.getLast7Days();
      const userData = [10, 15, 20, 25, 30, 35, 40];
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['新增用户', '活跃用户']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '新增用户',
            type: 'line',
            stack: '总量',
            data: userData,
            smooth: true,
            areaStyle: {}
          },
          {
            name: '活跃用户',
            type: 'line',
            stack: '总量',
            data: userData.map(v => v * 2),
            smooth: true,
            areaStyle: {}
          }
        ]
      };
      
      this.userGrowthChart.setOption(option);
    },
    // 初始化内容统计图表
    initContentStatsChart() {
      if (this.contentStatsChart) {
        this.contentStatsChart.dispose();
      }
      
      this.contentStatsChart = echarts.init(this.$refs.contentStatsChart);
      
      // 这里使用模拟数据，实际应该使用API返回的数据
      const dates = this.getLast7Days();
      const postData = [5, 8, 12, 15, 18, 22, 25];
      const commentData = [10, 15, 20, 25, 30, 35, 40];
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['新增帖子', '新增评论']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '新增帖子',
            type: 'line',
            data: postData,
            smooth: true
          },
          {
            name: '新增评论',
            type: 'line',
            data: commentData,
            smooth: true
          }
        ]
      };
      
      this.contentStatsChart.setOption(option);
    },
    // 获取最近7天的日期
    getLast7Days() {
      const dates = [];
      for (let i = 6; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        dates.push(this.formatDate(date));
      }
      return dates;
    },
    // 格式化日期
    formatDate(date) {
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${month}/${day}`;
    },
    // 调整图表大小
    resizeCharts() {
      if (this.userGrowthChart) {
        this.userGrowthChart.resize();
      }
      if (this.contentStatsChart) {
        this.contentStatsChart.resize();
      }
    },
    // 跳转到圈子详情
    goToTopicDetail(row) {
      this.$router.push({ path: '/quanzi/topic', query: { topicId: row.topicId } });
    },
    // 跳转到帖子详情
    goToPostDetail(row) {
      this.$router.push({ path: '/quanzi/post', query: { postId: row.postId } });
    },
    // 跳转到用户详情
    goToUserDetail(row) {
      this.$router.push({ path: '/quanzi/user', query: { userId: row.userId } });
    }
  }
};
</script>

<style scoped>
.dashboard-count {
  margin-bottom: 20px;
}
.count-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 4px;
  background-color: #f8f8f8;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.count-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #F56C6C;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}
.count-icon .svg-icon {
  width: 30px;
  height: 30px;
  color: #fff;
}
.count-info {
  flex: 1;
}
.count-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}
.count-num {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}
.chart-container {
  position: relative;
  width: 100%;
  height: 300px;
}
</style>